import { login, sysProfile, sysUser } from '@/api/user.js'
import { getToken, setToken } from '@/utils/auth.js'
import asyncRoutes from '@/router/modules/index.js'
import router from '@/router'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken (state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo (state, value) {
    state.userInfo = value
  },
  // 退出登录时
  layout (state) {
    // 清空储存的token和用户信息
    state.token = ''
    setToken('')
    state.userInfo = ''
    // 重置路由
    resetRouter()
  }
}
const getters = {}
const actions = {
  // 登录调用
  async getLogin (store, value) {
    const res = await login(value)
    console.log('user', res)
    // 储存token
    store.commit('setToken', res.data)
  },
  // 调用用户个人资料
  async getUserInfo (store) {
    const res = await sysProfile()
    // 调用员工基本资料
    const res2 = await sysUser(res.data.userId)
    // console.log('用户资料', res, res2)
    // 将两个资料合并储存用户信息
    store.commit('setUserInfo', { ...res.data, ...res2.data })
    // 将用户信息中的权限数据与动态路由配置匹配，将匹配项的路由配置添加到路由中
    const newArr = asyncRoutes.filter(item => {
      return store.state.userInfo.roles.menus.includes(item.name)
    })
    // 添加的路由不能立马使用，会立马匹配到404，所以要将404匹配路由最后动态添加
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    console.log('newArr:', newArr)
    // 本模块调用其他模块的mutations方法
    store.commit('routers/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
    // 将匹配项添加到路由配置中，router.addRoutes([路由配置]),添加新的路由配置
    router.addRoutes(newArr)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
